package com.bingoogolapple.qrcode.core;

import ohos.agp.render.*;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.Point;
import ohos.agp.utils.Rect;
import ohos.agp.utils.RectFloat;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.TouchEvent;

public class BGAQRCodeUtil {
    private static boolean debug;

    public static void setDebug(boolean debug) {
        BGAQRCodeUtil.debug = debug;
    }

    public static boolean isDebug() {
        return debug;
    }

    public static void d(String msg) {
        d("BGAQRCode", msg);
    }

    public static void printRect(String prefix, Rect rect) {
        d("BGAQRCodeFocusArea", prefix + " centerX：" + rect.left + " centerY：" + rect.top + " width：" + rect.getWidth() + " height：" + rect.getHeight()
                + " rectHalfWidth：" + rect.getWidth() / 2 + " rectHalfHeight：" + rect.getHeight() / 2
                + " left：" + rect.left + " top：" + rect.top + " right：" + rect.right + " bottom：" + rect.bottom);
    }

    public static void d(String tag, String msg) {
        if (debug) {
            LogUtil.info(msg);
        }
    }

    public static void e(String msg) {
        if (debug) {
            LogUtil.info(msg);
        }
    }

    /*
     * 是否为竖屏
     */
    public static boolean isPortrait(Context context) {
        Point screenResolution = getScreenResolution(context);
        return screenResolution.getPointY() > screenResolution.getPointX();
    }

    static Point getScreenResolution(Context context) {
        return DeviceUtil.getDisplayAttributes(context);
    }

    public static int getStatusBarHeight(Context context) {
        return 0;
    }

    public static int dp2px(Context context, float dpValue) {
        return (int) dpValue * (int) DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes().densityPixels;

    }

    public static int sp2px(Context context, float spValue) {
        return (int) spValue;
    }

    public static PixelMap adjustPhotoRotation(PixelMap inputBitmap, int orientationDegree) {
        if (inputBitmap == null) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(orientationDegree, (float) inputBitmap.getImageInfo().size.width / 2,
                (float) inputBitmap.getImageInfo().size.height / 2);
        float outputX, outputY;
        if (orientationDegree == 90) {
            outputX = inputBitmap.getImageInfo().size.height;
            outputY = 0;
        } else {
            outputX = inputBitmap.getImageInfo().size.height;
            outputY = inputBitmap.getImageInfo().size.width;
        }
        float[] values = new float[9];
        values = matrix.getData();
        float x1 = values[2];
        float y1 = values[5];
        matrix.postTranslate(outputX - x1, outputY - y1);
        PixelMap pixelMap = CanvasUtil.createPixelMap(inputBitmap.getImageInfo().size.height,inputBitmap.getImageInfo().size.width);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(new Texture(pixelMap));
        canvas.setMatrix(matrix);
        canvas.drawPixelMapHolder(new PixelMapHolder(inputBitmap),0,0,paint);
        return pixelMap;
    }

    public static PixelMap makeTintBitmap(PixelMap inputBitmap, int tintColor) {
        if (inputBitmap == null) {
            return null;
        }

        PixelMap pixelMap = CanvasUtil.createPixelMap(inputBitmap.getImageInfo().size.height,inputBitmap.getImageInfo().size.width);
        Canvas canvas = new Canvas(new Texture(pixelMap));
        Paint paint = new Paint();
        paint.setColorFilter(new ColorFilter(tintColor, BlendMode.SRC_IN));
        canvas.drawPixelMapHolder(new PixelMapHolder(inputBitmap),0,0,paint);
        return pixelMap;
    }

    /**
     * 计算对焦和测光区域
     *
     * @param coefficient        比率
     * @param originFocusCenterX 对焦中心点X
     * @param originFocusCenterY 对焦中心点Y
     * @param originFocusWidth   对焦宽度
     * @param originFocusHeight  对焦高度
     * @param previewViewWidth   预览宽度
     * @param previewViewHeight  预览高度
     * @return Rect 矩形框
     */
    static Rect calculateFocusMeteringArea(float coefficient,
                                           float originFocusCenterX, float originFocusCenterY,
                                           int originFocusWidth, int originFocusHeight,
                                           int previewViewWidth, int previewViewHeight) {

        int halfFocusAreaWidth = (int) (originFocusWidth * coefficient / 2);
        int halfFocusAreaHeight = (int) (originFocusHeight * coefficient / 2);

        int centerX = (int) (originFocusCenterX / previewViewWidth * 2000 - 1000);
        int centerY = (int) (originFocusCenterY / previewViewHeight * 2000 - 1000);

        RectFloat rectF = new RectFloat(BGAQRCodeUtil.clamp(centerX - halfFocusAreaWidth, -1000, 1000),
                BGAQRCodeUtil.clamp(centerY - halfFocusAreaHeight, -1000, 1000),
                BGAQRCodeUtil.clamp(centerX + halfFocusAreaWidth, -1000, 1000),
                BGAQRCodeUtil.clamp(centerY + halfFocusAreaHeight, -1000, 1000));
        return new Rect(Math.round(rectF.left), Math.round(rectF.top),
                Math.round(rectF.right), Math.round(rectF.bottom));
    }

    static int clamp(int value, int min, int max) {
        return Math.min(Math.max(value, min), max);
    }

    /*
     * 计算手指间距
     */
    static float calculateFingerSpacing(TouchEvent event) {

        float x = event.getPointerScreenPosition(0).getX() - event.getPointerScreenPosition(1).getX();
        float y = event.getPointerScreenPosition(0).getY() - event.getPointerScreenPosition(1).getY();
        return (float) Math.sqrt(x * x + y * y);
    }

    /**
     * 将本地图片文件转换成可解码二维码的 Bitmap。为了避免图片太大，这里对图片进行了压缩。感谢 https://github.com/devilsen 提的 PR
     *
     * @param context 上下文对象
     * @param picturePath 本地图片文件路径
     * @return PixelMap图像
     */
    public static PixelMap getDecodeAbleBitmap(Context context, String picturePath) {
        try {
            return ResourceUtil.getPixelMapByExtPath(context,picturePath);
        } catch (Exception e) {
            LogUtil.info(e.getMessage());
            return null;
        }
    }
}